<script setup>
import { ref, reactive, watch, onMounted, h, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useCurrentWatchStore } from '@T2/store/users.ts';
import { devicegroupApi as MainApi, devicegroupById as MainById, devicegroupkeyApi, devicegroupkeyById } from '@T2/service/api.ts';
import { VueDraggable } from 'vue-draggable-plus'

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;

const props = defineProps({
  unit: {
    type: Object,
    required: true,
  }
});
const emits = defineEmits(['pagesChange']);

onMounted(() => {
  GetMainTable();
});

const MainTable = reactive({
  data: [],
  total: 0,
  dragDisabled: false,
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  search: '',
});
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  MainApi({
    method: 'get',
    params: {
      ...Filter,
      ordering: 'index',
      
      unit: props.unit.id,
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
    
    MainTable.dragDisabled = false;
  });
}

/* 新增编辑 */
const MainPopup = reactive({
  visible: false,
  type: '新增',
});
const MainForm = reactive({
  model: {},
});
const MainFormRef = ref(null);
const handleMainAdd = () => {
  MainPopup.visible = true;
  MainPopup.type = '新增';
  MainForm.model = {};
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainEdit = (row) => {
  MainPopup.visible = true;
  MainPopup.type = '编辑';
  MainForm.model = {
    id: row.id,
    name: row.name,
    mark: row.mark,
  };
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainSubmit = () => {
  MainFormRef.value.validate((valid) => {
    if (valid) {
      MainPopup.visible = false;
      if (MainPopup.type === '新增') {
        AddMain();
      } else if (MainPopup.type === '编辑') {
        EditMain();
      }
    }
  });
}
const AddMain = () => {
  MainApi({
    method: 'post',
    data: {
      ...MainForm.model,
      project: curProject.id,
      unit: props.unit.id,
      index: MainTable.data.length + 1,
    }
  }).then(res => {
    ElMessage.success('新增成功');
    GetMainTable();
  });
}
const EditMain = () => {
  MainById({
    method: 'patch',
    id: MainForm.model.id,
    data: {
      ...MainForm.model,
    }
  }).then(res => {
    ElMessage.success('编辑成功');
    GetMainTable();
  });
}
const handleMainDelete = (row) => {
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `您是否要删除 ${ row.name }？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainById({
      method: 'delete',
      id: row.id,
    }).then(res => {
      ElMessage.success('删除成功');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}
/* 拖拽排序 */
const onMainUpdate = async (e) => {
  MainTable.dragDisabled = true;
  for (const [index, item] of MainTable.data.entries()) {
    if (item.index === index + 1) {
      continue;
    }
    await changeIndexMainTable(item.id, index + 1);
  }
  ElMessage.success('排序加载完成');
  GetMainTable();
}
const changeIndexMainTable = async (id, index) => {
  return new Promise((resolve, reject) => {
    MainById({
      method: 'patch',
      id,
      data: {
        index,
      }
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  });
}

/* 参数管理 */
const KeyPopup = reactive({
  visible: false,
});
const KeyTable = reactive({
  data: [],
  dragDisabled: false,
  currentDevicegroup: null,
  editRow: null,
});
const handleKeyPopup = (row) => {
  KeyPopup.visible = true;
  KeyTable.currentDevicegroup = { ...row };
  KeyTable.data = [];
  GetKeyTable();
}
const GetKeyTable = () => {
  devicegroupkeyApi({
    method: 'get',
    params: {
      page: 1,
      devicegroup: KeyTable.currentDevicegroup.id,
      ordering: 'index',
    }
  }).then(res => {
    KeyTable.data = res?.results || [];
    
    KeyTable.dragDisabled = false;
  });
}
const handleKeyAdd = () => {
  KeyTable.data.unshift({
    name: '',
    type: '字符串',
    index: KeyTable.data.length + 1,
  });
  KeyTable.editRow = 0;
}
const handleKeyEdit = (row, index) => {
  KeyTable.editRow = index;
}
const handleKeyCancle = (row, index) => {
  KeyTable.editRow = null;
  if (!row.id) {
    KeyTable.data.splice(index, 1);
  }
}
const handleKeySave = (row) => {
  KeyTable.editRow = null;
  if (row.id) {
    EditKey(row);
  } else {
    AddKey(row);
  }
}
const AddKey = (row) => {
  devicegroupkeyApi({
    method: 'post',
    data: {
      project: curProject.id,
      devicegroup: KeyTable.currentDevicegroup.id,
      index: row.index,
      name: row.name,
      type: row.type,
    }
  }).then(res => {
    ElMessage.success('新增参数成功');
    GetKeyTable();
  });
}
const EditKey = (row) => {
  devicegroupkeyById({
    method: 'patch',
    id: row.id,
    data: {
      index: row.index,
      name: row.name,
      type: row.type,
    }
  }).then(res => {
    ElMessage.success('编辑参数成功');
    GetKeyTable();
  });
}
const handleKeyDelete = (row) => {
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `您是否要删除参数 ${ row.name }？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    devicegroupkeyById({
      method: 'delete',
      id: row.id,
    }).then(res => {
      ElMessage.success('删除成功');
      GetKeyTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}
/* 拖拽排序 */
const onKeyUpdate = async (e) => {
  KeyTable.dragDisabled = true;
  for (const [index, item] of KeyTable.data.entries()) {
    if (item.index === index + 1) {
      continue;
    }
    await changeIndexKeyTable(item.id, index + 1);
  }
  ElMessage.success('排序加载完成');
  GetKeyTable();
}
const changeIndexKeyTable = async (id, index) => {
  return new Promise((resolve, reject) => {
    devicegroupkeyById({
      method: 'patch',
      id,
      data: {
        index,
      }
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  });
}

const backToDeviceList = () => {
  emits('pagesChange', '');
}

</script>

<template>
  <div class="view flex-column">
    <div class="nav-line">
      <el-breadcrumb separator-icon="ArrowRight">
        <el-breadcrumb-item @click="backToDeviceList()">{{ props.unit.name }}</el-breadcrumb-item>
        <el-breadcrumb-item class="isActive">管理设备组</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <div class="devicegroup-box flex-column mainCard">
      <el-form label-width="120px" class="flex--center t_form">
        <p class="title-name">站点设备组管理</p>
        <div class="flex r_btn">
          <el-button type="primary" @click="handleMainAdd()">新增</el-button>
        </div>
      </el-form>
      
      <VueDraggable
        v-model="MainTable.data"
        target="tbody"
        :disabled="MainTable.dragDisabled"
        @update="onMainUpdate"
        :animation="150"
      >
        <el-table :data="MainTable.data" scrollbar-always-on>
          <el-table-column label="序号" prop="index" min-width="80px" align="center" fixed="left"></el-table-column>
          <el-table-column label="设备组名称" prop="name" min-width="200px" show-overflow-tooltip></el-table-column>
          <el-table-column label="备注" prop="mark" min-width="600px"></el-table-column>
          <el-table-column label="操作" fixed="right" align="center" min-width="200px">
            <template #default="scope">
              <el-button link type="primary" @click="handleKeyPopup(scope.row)">管理参数</el-button>
              <el-button link type="primary" @click="handleMainEdit(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="handleMainDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </VueDraggable >
      
      <el-pagination
        layout="->, total, prev, pager, next, sizes"
        background 
        :page-sizes="[10, 20, 30, 50, 100]"
        :pager-count="5"
        v-model:currentPage="Filter.page"
        v-model:page-size="Filter.pagesize"
        :total="MainTable.total"
      />
    </div>
  </div>
  
  <!-- 新增编辑 -->
  <el-dialog width="500px" :title="MainPopup.type + '设备组'" v-model="MainPopup.visible">
    <el-form
      ref="MainFormRef"
      :model="MainForm.model"
      label-width="120px"
    >
      <el-form-item prop="name" label="设备组名称：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
        <el-input v-model="MainForm.model.name"></el-input>
      </el-form-item>
      <el-form-item prop="mark" label="备注：">
        <el-input v-model="MainForm.model.mark"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="MainPopup.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleMainSubmit()" v-prevent-rapid-click>确 定</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 参数管理 -->
  <el-dialog width="600px" title="设备组参数管理" v-model="KeyPopup.visible">
    <div class="devicegroupkey-title flex--center">
      <label>设备组名称：</label>
      <span>{{ KeyTable.currentDevicegroup?.name }}</span>
      <el-button link type="primary" style="margin-left: auto;" @click="handleKeyAdd()" v-show="KeyTable.editRow === null">
        <el-icon><CirclePlus /></el-icon>
        <span>添加参数</span>
      </el-button>
    </div>
    <VueDraggable
      v-model="KeyTable.data"
      target="tbody"
      :disabled="KeyTable.dragDisabled || KeyTable.editRow"
      @update="onKeyUpdate"
      :animation="150"
    >
      <el-table :data="KeyTable.data" :max-height="500" scrollbar-always-on>
        <el-table-column label="序号" prop="index" width="80px">
          <template #default="scope">
            <el-input
              v-if="KeyTable.editRow === scope.$index"
              v-model="scope.row.index"
            />
            <span v-else>{{ scope.row.index }}</span>
          </template>
        </el-table-column>
        <el-table-column label="参数名称" prop="name" width="200px" show-overflow-tooltip>
          <template #default="scope">
            <el-input
              v-if="KeyTable.editRow === scope.$index"
              v-model="scope.row.name"
            />
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="字段类型" prop="type" width="135px">
          <template #default="scope">
            <el-select v-model="scope.row.type" v-if="KeyTable.editRow === scope.$index">
              <el-option value="字符串" label="字符串"></el-option>
              <el-option value="日期" label="日期"></el-option>
            </el-select>
            <span v-else>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="150px">
          <template #default="scope">
            <template v-if="KeyTable.editRow === scope.$index">
              <el-button link type="primary" @click="handleKeySave(scope.row)">保存</el-button>
              <el-button link type="primary" @click="handleKeyCancle(scope.row, scope.$index)">取消</el-button>
            </template>
            <template v-else-if="KeyTable.editRow === null">
              <el-button link type="primary" @click="handleKeyEdit(scope.row, scope.$index)">编辑</el-button>
              <el-button link type="danger" @click="handleKeyDelete(scope.row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </VueDraggable >
      
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="KeyPopup.visible = false;KeyTable.editRow = null;">关 闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.nav-line {
  height: 30px;
  padding: 12px 12px 6px;
}
.devicegroup-box {
  flex: 1;
  overflow: hidden;
  position: relative;
}
.title-name {
  font-weight: 500;
  font-size: 16px;
  color: #4C4C4C;
}
.devicegroupkey-title {
  font-size: 14px;
  color: #4C4C4C;
  margin-bottom: 12px;
  label {
    color: #888888;
    font-size: 14px;
  }
}
</style>

<style scoped>
:deep(.el-form) {
  margin-bottom: 18px;
}
:deep(.el-breadcrumb__inner) {
  cursor: pointer !important;
}
:deep(.el-breadcrumb__item.isActive .el-breadcrumb__inner) {
  color: #0079FE;
  cursor: default !important;
}
</style>